package com.example.myapplication.ui.news.NewsPresenter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;

import com.example.myapplication.api.HostType;
import com.example.myapplication.base.RxPresenter;
import com.example.myapplication.model.bean.VideoData;
import com.example.myapplication.model.https.RetrofitHelpers;
import com.example.myapplication.model.rx.RxSubscriber;
import com.example.myapplication.ui.wight.LoadingDialog;
import com.example.myapplication.utils.TimeUtil;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by meishiyiyun on 2017/6/14.
 */

public class VideoListPresenter extends RxPresenter<VideosListContract.View> implements VideosListContract.Presenter{
    private  Context mContext;
    public VideoListPresenter(Context context) {
        this.mContext=context;
    }

    @Override
    public void requestDataRefresh(String type, int startPage) {
        Dialog dialog= LoadingDialog.showDialogForLoading((Activity) mContext, "加载中...",false,false);
        getVideosListData(type,startPage).subscribe(new RxSubscriber<List<VideoData>>(dialog) {
            @Override
            protected void _onNext(List<VideoData> videoDatas) {
                mView.SuccessRefresh(videoDatas);
            }

            @Override
            protected void _onError(String message) {

            }
        });
    }


    Observable<List<VideoData>> getVideosListData(String type, int startPage){
        return RetrofitHelpers.getInstance(HostType.NETEASE_NEWS_VIDEO,false).getVideoList(type,startPage)
                .flatMap(stringListMap ->{
                    return  Observable.fromIterable(stringListMap.get(type));
                        })
                .map(videoData  ->{
                         String ptime = TimeUtil.formatDate(videoData.getPtime());
                        videoData.setPtime(ptime);
                           return videoData;
                     })
              .distinct().toSortedList((o1, o2) ->     o2.getPtime().compareTo(o1.getPtime()))
              .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).toObservable();
    }
}
